package heven.holt.eyepetizer.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import heven.holt.eyepetizer.api.ApiMainPageService
import heven.holt.eyepetizer.model.BasePageModel

class CommendPagingSource(private val mainPageService: ApiMainPageService) :
    PagingSource<String, BasePageModel.Item>() {

    override suspend fun load(params: LoadParams<String>): LoadResult<String, BasePageModel.Item> {
        return try {
            val page = params.key ?: ApiMainPageService.HOMEPAGE_RECOMMEND_URL
            val repoResponse = mainPageService.getHomePageRecommend(page)
            val repoItems = repoResponse.itemList
            val nextKey =
                if (!repoItems.isNullOrEmpty() && !repoResponse.nextPageUrl.isNullOrEmpty()) repoResponse.nextPageUrl else null
            LoadResult.Page(
                repoItems ?: emptyList(),
                if (page == ApiMainPageService.HOMEPAGE_RECOMMEND_URL) null else page,
                nextKey
            )
        } catch (e: Exception) {
            e.printStackTrace()
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<String, BasePageModel.Item>): String = ApiMainPageService.HOMEPAGE_RECOMMEND_URL
}